package com.ideaaedi.zoo.diy.feature.msg.mq.impl.rocketmq.core;

import com.ideaaedi.zoo.diy.feature.msg.api.mq.core.MqSender;
import com.ideaaedi.zoo.diy.feature.msg.api.mq.entity.MqSendOption;
import com.ideaaedi.zoo.diy.feature.msg.api.mq.entity.MqSendResult;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.util.MimeType;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * (non-javadoc)
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 1.0.0
 */
public class StreamRocketMQSender implements MqSender {
    
    private final StreamBridge streamBridge;
    
    public StreamRocketMQSender(StreamBridge streamBridge) {
        this.streamBridge = streamBridge;
    }
    
    @Nonnull
    @Override
    public String id() {
        return "default-rocketmq";
    }
    
    @Nonnull
    @Override
    public String supplier() {
        return "rocketmq-spring-cloud-stream";
    }
    
    @Override
    public List<String> tags() {
        return Collections.emptyList();
    }
    
    @Override
    public MqSendResult send(@Nonnull String channel, @Nonnull Object data, @Nullable MqSendOption option) {
        String binderName = Optional.ofNullable(option).map(MqSendOption::getBinderName).orElse(null);
        MimeType mimeType = Optional.ofNullable(option).map(MqSendOption::getMimeType).orElse(null);
        boolean result;
        if (mimeType != null) {
            result = streamBridge.send(channel, binderName, data, mimeType);
        } else {
            result = streamBridge.send(channel, binderName, data);
        }
        MqSendResult mqSendResult = new MqSendResult();
        mqSendResult.setSuccess(result);
        mqSendResult.setRaw(result);
        return mqSendResult;
    }
}
